import ajax from '../../common/js/ajax'
import router from '@ohos.router'
import data_storage from '@ohos.data.storage';
import featureAbility from '@ohos.ability.featureAbility'

export default {
    data: {
        goodsId:0,
        goodsInfo:{},
        collection:false,
        conditionIcon:'/common/icon/收藏.png'
    },
    onInit() {
        console.log("测试：" + 'hello')
        let goodsId= router.getParams()['goodsId']
//        console.log(goodsId)
        if (!goodsId) {
            return router.back()
        }
        this.goodsId = goodsId
        this.getGoodsInfo()
    },
    favorite(){
        this.collection = !this.collection
        if (this.collection) {
            this.conditionIcon = '/common/icon/收藏选中.png'
        }else {
            this.conditionIcon = '/common/icon/收藏.png'
        }
    },
    back(){
        router.back();
    },
    getGoodsInfo(){
        ajax.get({
            url:'http://124.71.79.186:8081/commodity/findGoods?goodsId='+this.goodsId,
            success:resp=>{
                if (resp.code === 200) {
                    this.goodsInfo = resp.data
//                    console.log(JSON.stringify(this.goodsInfo))
                }
            }
        })
    },
    gotoShoppingCart(){
        router.push({
            url: 'pages/shoppingCart/shoppingCart',
        })
    },
    addGoods() {
        let goods = this.goodsInfo
        var context = featureAbility.getContext();
        context.getFilesDir().then((filePath) => {
            let storage = data_storage.getStorageSync(filePath + '/myStore')

            let goodsList = JSON.parse(storage.getSync('goodsList', JSON.stringify([])))
            const existingGoods = goodsList.find(g => g.id === goods.id)
            if (existingGoods) {
                existingGoods.buyNum++
            } else {
                goodsList.push({
                    ...goods,
                    buyNum: 1,
                    checked: false
                })
            }

            storage.putSync('goodsList', JSON.stringify(goodsList))
            storage.flushSync()

        });
    }
}
